package com.cgb2110.serve.controller;


import com.cgb2110.serve.pojo.Admin;
import com.cgb2110.serve.pojo.MailConstants;
import com.cgb2110.serve.pojo.RespBean;
import com.cgb2110.serve.pojo.Salary;
import com.cgb2110.serve.service.impl.AdminServiceImpl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Larry
 * @since 2021-12-20
 */
@RestController
@RequestMapping("/system/admin")
public class AdminController {
    @Autowired
    private AdminServiceImpl adminService;

    @ApiOperation(value = "获取所有操作人员")
    @GetMapping("/")
    public List<Admin> getAllAdmins(String keywords){
        return adminService.getAllAdmins(keywords);
    }

    @ApiOperation(value = "修改操作员信息")
    @PutMapping("/")
    public RespBean updateAdmin(@RequestBody Admin admin){
        if (adminService.updateById(admin)){
            return RespBean.success("修改成功");
        }
        return RespBean.error("修改失败");
    }
    @ApiOperation(value = "删除操作员信息")
    @DeleteMapping("/{id}")
    public RespBean deleteAdminById(@PathVariable Integer id){
        if (adminService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }
    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null,authentication.getAuthorities()));
        return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }
    @ApiOperation(value = "更新用户名")
    @PutMapping("/pass")
    public RespBean updateAdminPassword(@RequestBody Map<String,Object> info){
       String oldPass = (String) info.get("oldPass");
       String pass = (String) info.get("pass");
       Integer adminId = (Integer) info.get("adminId");
       return adminService.updateAdminPassword(oldPass,pass,adminId);
    }
}
